#include <stdio.h>
#include <unistd.h>
#include <ctime>
#include <iostream>
#include <pthread.h>
#include <thread>
#include <memory>

#include "date.h"

using namespace std;

int step = 30;
struct tm *info;
int buffSize = 60;

int global =0 ;

void outputStr(std::string name)
{
    // cout << name << endl;
    printf("tid %d , value : %s\n", std::this_thread::get_id(), name.c_str());
}

void DateTst::forDateString2(time_t now, string &result)
{
    char buffer[buffSize];
    info = localtime(&now);
    strftime(buffer, buffSize, "%Y-%m-%d %H:%M:%S %A", info);
    result.assign(buffer);
}

void DateTst::formatDate(time_t now, char *buffer, int buffsize)
{
    info = localtime(&now);
    strftime(buffer, buffSize, "%Y-%m-%d %H:%M:%S %A", info);
}

string DateTst::forDateString(time_t now)
{
    char buffer[buffSize];
    info = localtime(&now);
    strftime(buffer, buffSize, "%Y-%m-%d %H:%M:%S %A", info);
    return string(buffer);
}

void DateTst::outputDate(void)
{
    time_t now = time(0);
    char *dt = ctime(&now);
    cout << "本地日期和时间 : " << dt << endl;

    char dateFormatResult[buffSize];
    formatDate(now, dateFormatResult, buffSize);
    cout << "本地日期和时间：" << dateFormatResult << endl;

    string dateResult = forDateString(now);
    const char *result = dateResult.c_str();

    cout << "本地日期和时间：" << result << endl;
    string newResult;
    forDateString2(now, newResult);
    cout << "本地日期和时间：" << newResult << endl;
}

int64_t DateTst::thread1()
{
    outputStr("sss  thread1");
    do
    //for (int i = 0; i < step; i++)
    {
        outputStr("for thread1");
        sleep(1);
        // outputDate();
    } while (true);

    return 0;
}

void *thread2(void *param)
{
    outputStr("thread22");
    for (int i = 0; i < step; i++)
    {
        printf("%s: %d: thread2: %d\n", __FILE__, __LINE__, i);
        usleep(1000000); // 休眠 1s
    }
    return (void *)0;
}

void DateTst::createThread()
{
    pthread_t pd1, pd2;
    int error;
    outputStr("start create thread1");
    error = pthread_create(&pd1, NULL, doThread1, this);
    if (error)
    {
        printf("创建线程1失败：%d\n", error);
    }

    // outputStr("start create thread2");
    // error = pthread_create(&pd2, NULL, thread2, NULL);
    // if (error)
    // {
    //     printf("创建线程2失败：%d\n", error);
    // }

    pthread_join(pd1, NULL);
}
int main()
{
    shared_ptr<DateTst> pDate = make_shared<DateTst>();
    pDate->createThread();
}

/**
 * 编译方法，需要手动连接动态库
 * g++ date.cpp  -o main -lpthread && ./main
 **/